package com.sairobo.live.auth;

import com.sairobo.live.util.AccessStateHelper;
import com.sairobo.live.web.vo.response.ResponseStatus;
import com.sairobo.live.token.TokenServiceFeign;
import com.sairobo.live.util.SpringUtil;
import com.sairobo.live.util.TokenUtils;
import com.netflix.zuul.context.RequestContext;
import io.jsonwebtoken.Claims;

import java.io.IOException;

/**
 * token令牌校验抽象类
 * <p>
 * Created by sdevil507 on 2017/4/28.
 */
public abstract class TokenAuth {

    /**
     * 校验器拦截的url(用于判断请求是否属于该校验器)
     */
    protected String[] urlPatterns;

    /**
     * token前缀,用于区分对应鉴权实现
     */
    protected String prefix = "";

    /**
     * token服务提供
     */
    protected TokenServiceFeign tokenServiceFeign;

    public TokenAuth(String prefix, String[] urlPatterns, TokenServiceFeign tokenServiceFeign) {
        this.prefix = prefix;
        this.urlPatterns = urlPatterns;
        this.tokenServiceFeign = tokenServiceFeign;
    }

    /**
     * 执行校验
     */
    public void run(RequestContext ctx, String token) throws IOException {
        TokenUtils tokenUtils = SpringUtil.getBean(TokenUtils.class);
        Claims claims = tokenUtils.getClaimsByToken(token);
        //暂时直接检验jwt是否过期
        if(!tokenUtils.isValidJwtToken(claims)){//JWT无效时返回处理逻辑
            AccessStateHelper.responseHandler(ctx, ResponseStatus.INVALID_TOKEN);
        }else {
            //如果存在该token,执行细化的具体验证,由各子类实现
            tokenAvailable(ctx,token,claims);
        }
    }

    /**
     * 当前token可用执行逻辑
     */
    protected abstract void tokenAvailable(RequestContext requestContext,String token, Claims claims);

    public String getPrefix() {
        return prefix;
    }
}
